package top.xzxsrq.datahelp.zhixin.module.file.service.impl;

import com.alibaba.fastjson.JSON;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.xzxsrq.common.utils.MyFileUtils;
import top.xzxsrq.common.utils.MyNumberUtils;
import top.xzxsrq.datahelp.zhixin.config.FileConfig;
import top.xzxsrq.datahelp.zhixin.module.file.entity.FileTable;
import top.xzxsrq.datahelp.zhixin.module.file.entity.FileTableCol;
import top.xzxsrq.datahelp.zhixin.module.file.entity.RelaFile;
import top.xzxsrq.datahelp.zhixin.module.file.service.FileService;
import top.xzxsrq.datahelp.zhixin.module.socket.service.WebSocketService;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.*;

/**
 * @program: datahelp
 * @create: 2021-11-22 18:04
 **/
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private FileConfig fileConfig;

    @Autowired
    private WebSocketService webSocketService;

    @Override
    public synchronized Map<String, FileTable> readFileMap() throws IOException {
        Map<String, FileTable> result = new LinkedHashMap<>();
        Iterator<File> fileIterator = MyFileUtils.iterateFiles(new File(this.fileConfig.getFileBasePath()), new String[]{FileConfig.SUFFIX}, false);
        while (fileIterator.hasNext()) {
            File next = fileIterator.next();
            if (MyFileUtils.isDirectory(next)) {
                continue;
            }
            String name = next.getName();
            boolean zhixin_relationship_ = name.startsWith(FileConfig.RELATION_FILE_PRE);
            FileTable item = new FileTable();
            item.setTableName(name);
            String fileToString = MyFileUtils.readFileToString(next, "UTF-8");
            List<FileTableCol> fileTableCols = JSON.parseArray(fileToString, FileTableCol.class);
            item.setCols(fileTableCols);
            if (!zhixin_relationship_) {
                result.put(name, item);
            }
        }
        return result;
    }

    @Override
    public synchronized void writeFile(FileTable fileTable, HttpServletRequest request) throws IOException {
        String tableName = fileTable.getTableName();
        String fileBasePath = this.fileConfig.getFileBasePath();
        String writeFile = fileBasePath + File.separator + tableName + "." + FileConfig.SUFFIX;
        MyFileUtils.write(new File(writeFile), JSON.toJSONString(fileTable.getCols()), "UTF-8");
        List<String> ids = new LinkedList<>();
        ids.add(request.getSession().getId());
        webSocketService.broadcastMsgNotId(MessageFormat.format("表格{0}已被修改", tableName), ids);
    }

    @Override
    public synchronized void writeRelaFile(List<RelaFile> file) throws IOException {
        Map<String, List<RelaFile>> stringFileTableMap = this.readRelaFile();
        if (MapUtils.isEmpty(stringFileTableMap)) {
            File file1 = MyFileUtils.createFile(this.fileConfig.getFileBasePath() + File.separator + FileConfig.RELATION_FILE_PRE + "0." + FileConfig.SUFFIX);
            MyFileUtils.write(file1, JSON.toJSONString(file), "UTF-8");
        } else {
            int lastName = 0;
            boolean hasAddAll = false;
            for (String key : stringFileTableMap.keySet()) {
                List<RelaFile> value = stringFileTableMap.get(key);
                int size = value.size();
                if (size < 1000) {
                    int canHas = 1000 - size;
                    if (file.size() <= canHas) {
                        value.addAll(file);
                        hasAddAll = true;
                    } else {
                        List<RelaFile> relaFiles = file.subList(0, canHas);
                        value.addAll(relaFiles);
                        file = file.subList(canHas + 1, file.size());
                    }
                    MyFileUtils.write(new File(this.fileConfig.getFileBasePath() + File.separator + key + "." + FileConfig.SUFFIX), JSON.toJSONString(value), "UTF-8");
                    if (hasAddAll) {
                        return;
                    }
                }
                lastName = MyNumberUtils.max(lastName, Integer.parseInt(key.replace(FileConfig.RELATION_FILE_PRE, "")));
            }
            lastName++;
            File file1 = MyFileUtils.createFile(this.fileConfig.getFileBasePath() + File.separator + FileConfig.RELATION_FILE_PRE + lastName + "." + FileConfig.SUFFIX);
            MyFileUtils.write(file1, JSON.toJSONString(file), "UTF-8");
        }
    }

    @Override
    public synchronized Map<String, List<RelaFile>> readRelaFile() throws IOException {
        Map<String, List<RelaFile>> result = new HashMap<>();
        Iterator<File> fileIterator = MyFileUtils.iterateFiles(new File(this.fileConfig.getFileBasePath()), new String[]{FileConfig.SUFFIX}, false);
        while (fileIterator.hasNext()) {
            File next = fileIterator.next();
            if (MyFileUtils.isDirectory(next)) {
                continue;
            }
            String name = next.getName();
            boolean zhixin_relationship_ = name.startsWith(FileConfig.RELATION_FILE_PRE);
            if (zhixin_relationship_) {
                String fileToString = MyFileUtils.readFileToString(next, "UTF-8");
                List<RelaFile> relaFiles = JSON.parseArray(fileToString, RelaFile.class);
                result.put(name, relaFiles);
            }
        }
        return result;
    }

    /**
     * 删除文件的同时还要删除文件的关联关系
     * @param name
     */
    @Override
    public void delFile(String name) {
        String path = this.fileConfig.getFileBasePath() + File.separator + name + FileConfig.SUFFIX;
        MyFileUtils.deleteFile(path);
    }
}
